# coding: utf-8

from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import permission_required, login_required
from django.shortcuts import render
from django.views.generic import TemplateView, ListView, View
from django.contrib.auth.models import Group, User, Permission, ContentType
from django.http import JsonResponse, HttpResponse, QueryDict, Http404
from django.core import serializers
from django.forms.models import model_to_dict
from django.conf import settings
import logging
logger = logging.getLogger("opsweb")

class GroupListView(ListView):
    model = Group
    template_name = "user/grouplist.html"

    def post(self, request):
        ret = { "status": 0 }
        group_name = request.POST.get("name", "")
        if group_name:
            try:
                Group.objects.create(name=group_name)
            except Exception as e:
                ret['status'] = 1
                ret['errmsg'] = e.args
        else:
            ret["status"] = 1
            ret['errmsg'] = "组名不能为空"
        return JsonResponse(ret, safe=True)

class GroupView(View):
    '''
    获取用户组信息
    '''
    def get(self, request):
        uid = request.GET.get("uid", None)
        ret = {"status": 0}
        try:
            user = User.objects.get(pk=uid)
        except User.DoesNotExist:
            ret['status'] = 1
            ret['errmsg'] = "用户不存在"

        try:
            all_groups = Group.objects.all()
            groups = [ group for group in all_groups if group not in user.groups.all() ]
        except Exception as e:
            ret['status'] = 1
            ret['errmsg'] = e.args
        return HttpResponse(serializers.serialize("json", groups), content_type="application/json")

class UserGroupView(View):
    """
        取出指定用户组下的所有用户信息
    """
    def get(self, request):
        gid = request.GET.get("gid", None)
        try:
            group = Group.objects.get(pk=gid)
        except:
            return JsonResponse([], safe=False)
        users = group.user_set.all()
        user_list = [ {"id": user.id, "username": user.username, "email": user.email, "name": user.profile.name} for user in users]
        return JsonResponse(user_list, safe=False)

    """
        将用户添加到指定组
    """
    def post(self, request):
        ret = {"status": 0}
        uid = request.POST.get("uid", None)
        gid = request.POST.get("gid", None)
        try:
            user = User.objects.get(pk=uid)
        except User.DoesNotExist:
            logger.error("将用户添加到指定用户组，用户不存在, 用户id为：{}".format(uid))
            ret['status'] = 1
            ret['errmsg'] = "用户不存在"
        try:
            group = Group.objects.get(pk=gid)
        except Group.DoesNotExist:
            logger.error("将用户添加到指定用户组，用户组不存在, 用户组id为：{}".format(gid))
            ret['status'] = 1
            ret['errmsg'] = "用户组不存在"
        user.groups.add(group)
        return JsonResponse(ret, safe=True)

    """
    删除组内指定用户
    """
    def delete(self, request):
        ret = { "status": 0 }
        data = QueryDict(request.body)
        uid = data.get("userid", None)
        gid = data.get("groupid", None)
        try:
            user = User.objects.get(pk=uid)
            group = Group.objects.get(pk=gid)
            group.user_set.remove(user)
        except User.DoesNotExist:
            ret['status'] = 1
            ret['errmsg'] = "用户不存在"
        except Group.DoesNotExist:
            ret['status'] = 1
            ret['errmsg'] = "用户组不存在"
        except Exception as e:
            ret['status'] = 1
            ret['errmsg'] = e.args
        return JsonResponse(ret, safe=True)

class GroupPermissionListView(TemplateView):
    template_name = 'user/group_permission_list.html'

    def get_context_data(self, **kwargs):
        context = super(GroupPermissionListView, self).get_context_data(**kwargs)
        context['content_type'] = ContentType.objects.all()
        context['group_permissions'] = self.get_group_permission()
        context['group'] = self.request.GET.get('gid', None)
        return context

    def get_group_permission(self):
        gid = self.request.GET.get('gid', None)
        try:
            group = Group.objects.get(pk=gid)
            return [ p.id for p in group.permissions.all()]
        except Group.DoesNotExist:
            raise Http404

    def post(self, request):
        ret = {"status": 0, "next_url": "/group/list/"}
        gid = request.POST.get("group", None)
        pids = request.POST.getlist("pids", [])
        try:
            group = Group.objects.get(pk=gid)
            if pids:
                group.permissions = Permission.objects.filter(id__in=pids)
            else:
                group.permissions = []
        except Exception as e:
            ret['status'] = 1
            ret['errmsg'] = e.args
        finally:
            return render(request, settings.TEMPLATE_JUMP, ret)

